'''Testbed for pyopencl.'''

import time
import numpy
import numpy.linalg as la
from ahh.util.opencl import SimpleDeviceContext

ticTime = time.time()
def tic(str=None):
    '''
    Saves the time and optionally prints a message. Follow with toc().

    Warning: Not thread safe.
    '''
    global ticTime
    if (str != None): print str
    ticTime = time.time()

def toc():
    '''
    Prints the elapsed time since the last call to tic like this:
    --> 10.3 s

    Returns the elapsed time in decimal seconds.
    '''
    elapsed = time.time() - ticTime
    #print "--> " + str(elapsed) + " s"
    return elapsed


## Create an OpenCL context
ctx = SimpleDeviceContext.create_somehow()
prg = ctx.compile("""
  __kernel void sum(__global int * const a)
    {
        int gid = get_global_id(0);
        a[gid] = get_num_groups(0)*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1*1;
    }

    __kernel void sum2(__global int * const a)
    {
        int gid = get_global_id(0);
        a[gid] = get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0)*get_num_groups(0);
    }
""")
out = numpy.empty(12800000, dtype=numpy.int32)
out_buf = ctx.alloc_like(out)
times = [ ]
for i in xrange(1000):
    tic()
    prg.sum((12800000,), out_buf)
    times.append(toc())

print float(sum(times))/len(times)
print out